import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes , allAsyncRoutes ,anyRoute} from '@/router/routes'
import { promiseTimeout } from '_@vueuse_shared@9.1.1@@vueuse/shared';
import usertInfoApi, { type IinfoModel } from "@/api/userInfo";
import type { RouteRecordRaw } from 'vue-router';
import router from "@/router"
import { cloneDeep } from 'lodash';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
interface userInfoStateModel {
  token: string,
  userInfo: IinfoModel,
  menuRoutes: RouteRecordRaw[]
}
interface resetUserInfoModel {
  name: string,
  avatar: string,
  buttons: string[],
  roles: string[],
  routes: string[]
}
const resetInfo = (): resetUserInfoModel => ({
  name: '',
  avatar: '',
  buttons: [],
  roles: [],
  routes: []
})

//权限菜单
//1-过滤权限菜单
const filterAsyncRoutes=(routes:RouteRecordRaw[],routeName:string[])=>{
  const result=routes.filter(item=>{
    
    if(item.children){
      item.children=filterAsyncRoutes(item.children,routeName)
    }
    return routeName.includes(item.name as string)
  });
  return result;
}

//2-动态路由注册
const addAsyncRoutes=(allRoutes:RouteRecordRaw[])=>{
  allRoutes.forEach(route=>{
      router.addRoute(route)
  })
}

export const useUserInfoStore = defineStore('userInfo', {

  // state: (): UserInfoState => ({
  //   token: getToken() as string,
  //   name: '',
  //   avatar: '',
  //   menuRoutes: []
  // }),
  state: (): userInfoStateModel => ({
    token: getToken() as string,
    userInfo: resetInfo(),
    menuRoutes: []
  }),

  actions: {
    async login(username: string, password: string) {
      try {
        let result = await usertInfoApi.login({ username, password });
        // console.log(result);
        setToken(result.token);
        this.token = result.token;
      } catch (err) {
        console.log(err);
        ElMessage.error('用户名或密码错误!');
        return Promise.reject(err)
      }
    },
    // login (username: string, password: string) {
    //   return new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //       if (username==='admin' && password==='111111') {
    //         const token = 'token-atguigu'
    //         setToken(token)
    //         this.token = token
    //         resolve(token)
    //       } else {
    //         reject(new Error('用户名或密码错误!'))
    //         ElMessage.error('用户名或密码错误!')
    //       }
    //     }, 1000)
    //   })
    // },
    async getInfo() {
      try {
        let result = await usertInfoApi.info();
        // console.log(result);
        this.userInfo = result;
        // this.menuRoutes = staticRoutes;

         
        const allRoutes=staticRoutes.concat(filterAsyncRoutes(cloneDeep(allAsyncRoutes),this.userInfo.routes))
        this.menuRoutes = allRoutes;

        addAsyncRoutes(allRoutes.concat(anyRoute));

      } catch (err) {
        console.log("获取用户信息失败", err);
        ElMessage.error('获取用户信息失败');
        return Promise.reject(err)
      }
    },
    // getInfo () {
    //   return new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //       this.name = 'admin'
    //       this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
    //       this.menuRoutes = staticRoutes
    //       resolve({name: this.name, avatar: this.avatar, token: this.token})
    //     }, 1000)
    //   })
    // },

    // reset () {
    //   // 删除local中保存的token
    //   removeToken()
    //   // 提交重置用户信息的mutation
    //   this.token = ''
    //   this.name = ''
    //   this.avatar = ''
    // },
   async  reset() {
      try {
        await usertInfoApi.logout();
        // 删除local中保存的token
        removeToken()
        // 提交重置用户信息的mutation
        this.token = ''
        // this.userInfo.name = ''
        // this.userInfo.avatar = ''
        this.userInfo = resetInfo();
      } catch (err) {
        // console.log("退出登录失败", err)
        ElMessage.error('退出登录出错');
        return Promise.reject(err)
      }
    },
  },
});
